package server

import (
	"easy-note/config"
	"easy-note/models"
	"easy-note/note/handler"
	"easy-note/note/kitex_gen/note/note"
	"easy-note/note/repo"
	"github.com/cloudwego/kitex/pkg/rpcinfo"
	"github.com/cloudwego/kitex/server"
	consul "github.com/kitex-contrib/registry-consul"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"net"
)

var svr server.Server

func Init() {
	conf := config.GetConfig()
	noteConf := conf.Server.Note
	dsn := conf.Mysql.GetDsnStr()
	r, err := consul.NewConsulRegister(conf.Consul.Addr)
	if err != nil {
		log.Fatalln(err)
	}
	addr, err := net.ResolveTCPAddr("tcp", noteConf.Addr)
	if err != nil {
		log.Fatalln(err)
	}
	svr = note.NewServer(new(handler.NoteImpl),
		server.WithServiceAddr(addr),
		server.WithRegistry(r),
		server.WithServerBasicInfo(&rpcinfo.EndpointBasicInfo{
			ServiceName: "easy-note.note",
		}))
	initDatabase(dsn)

}

func Start() {
	err := svr.Run()
	if err != nil {
		log.Fatalln(err)
	}
}

func initDatabase(dsn string) {
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatalln(err)
	}
	err = db.AutoMigrate(&models.User{}, &models.NoteInfo{})
	if err != nil {
		log.Fatalln(err)
	}
	repo.DB = db
}
